<template>
  <div class="viewContain">
    <el-form :model="listQuery" size="small" label-width="100px">
      <el-row>
        <el-col :xs="{ span: 24 }" :sm="{ span: 12 }" :md="{ span: 6 }" :xl="{ span: 6 }">
          <el-form-item label="订单号 :">
            <el-input
              v-model="listQuery.orderNum"
              placeholder="请输入内容"
              clearable
              @keyup.enter.native="handleSearch"
            />
          </el-form-item>
        </el-col>
        <el-col :xs="{ span: 24 }" :sm="{ span: 12 }" :md="{ span: 6 }" :xl="{ span: 6 }">
          <el-form-item label="账号名 :">
            <el-input
              v-model="listQuery.accountName"
              placeholder="请输入内容"
              clearable
              @keyup.enter.native="handleSearch"
            />
          </el-form-item>
        </el-col>
        <el-col :xs="{ span: 24 }" :sm="{ span: 12 }" :md="{ span: 6 }" :xl="{ span: 6 }">
          <el-form-item label="收货人姓名 :">
            <el-input
              v-model="listQuery.consigneeName"
              placeholder="请输入内容"
              clearable
              @keyup.enter.native="handleSearch"
            />
          </el-form-item>
        </el-col>
        <el-col :xs="{ span: 24 }" :sm="{ span: 12 }" :md="{ span: 6 }" :xl="{ span: 6 }">
          <el-form-item label="订单状态 :">
            <el-select v-model="listQuery.status" placeholder="请选择" clearable>
              <el-option
                v-for="item in orderStatus"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :xs="{ span: 24 }" :sm="{ span: 12 }" :md="{ span: 8 }" :xl="{ span: 8 }">
          <el-form-item label="起止时间 :">
            <el-date-picker
              v-model="listQuery.time"
              size="small"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              format="yyyy-MM-dd"
              value-format="yyyy-MM-dd"
              unlink-panels
              @change="dateChange"
            />
          </el-form-item>
        </el-col>
        <el-col :xs="{ span: 24 }" :sm="{ span: 12 }" :md="{ span: 8 }" :xl="{ span: 8 }">
          <el-form-item label-width="100px">
            <el-button size="mini" type="primary" @click="handleSearch">查询</el-button>
            <el-button size="mini" type="primary" plain @click="handleReload">重置</el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <div style="text-align:right;margin-bottom:10px">
      <el-button size="mini" type="primary" @click="handleExport">导出</el-button>
    </div>
    <!-- 发货 -->
    <el-dialog
      :title="dialogTitle_deliver"
      :visible.sync="dialogFormVisible_deliver"
      width="400px"
      :close-on-click-modal="false"
    >
      <el-form ref="formData_deliver" :model="formData_deliver" size="small" :rules="rules_deliver" label-width="100px">
        <el-row>
          <el-col :xs="{ span: 24 }" :sm="{ span: 24 }" :md="{ span: 24 }" :xl="{ span: 24 }">
            <el-form-item label="物流公司 :" prop="logistics">
              <el-select v-model="formData_deliver.logistics" filterable placeholder="请选择" style="width:100%" clearable>
                <el-option
                  v-for="item in logisticsList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.code"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :xs="{ span: 24 }" :sm="{ span: 24 }" :md="{ span: 24 }" :xl="{ span: 24 }">
            <el-form-item label="物流单号 :" prop="trackNum">
              <el-input v-model="formData_deliver.trackNum" placeholder="最多输入20字" clearable />
            </el-form-item>
          </el-col>
          <el-col :xs="{ span: 24 }" :sm="{ span: 24 }" :md="{ span: 24 }" :xl="{ span: 24 }">
            <el-form-item label="发货人 :" prop="shipper">
              <el-input v-model="formData_deliver.shipper" placeholder="最多输入20字" clearable />
            </el-form-item>
          </el-col>
        </el-row>
        <div style="text-align:center">
          <el-button size="mini" type="primary" plain @click="dialogFormVisible_deliver=false">取消</el-button>
          <el-button size="mini" type="primary" @click="handleSave_deliver">确定</el-button>
        </div>
      </el-form>
    </el-dialog>
    <!-- 异常处理 -->
    <el-dialog
      :title="dialogTitle_Abnormal"
      :visible.sync="dialogFormVisible_Abnormal"
      width="400px"
      :close-on-click-modal="false"
    >
      <el-form :model="formData_Abnormal" size="small" :rules="rules_Abnormal">
        <el-form-item label="异常信息 :" prop="name">
          <el-select v-model="formData_Abnormal.exceptionCause" placeholder="请选择" clearable>
            <el-option
              v-for="item in exceptionCause"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <div style="text-align:center">
          <el-button size="mini" type="primary" plain @click="dialogFormVisible_Abnormal=false">取消</el-button>
          <el-button size="mini" type="primary" @click="handleSave_Abnormal">确定</el-button>
        </div>
      </el-form>
    </el-dialog>
    <el-table
      ref="table"
      v-loading="loading"
      fit
      stripe
      :data="tableData"
      border
      size="mini"
    >
      <el-table-column align="center" label="序号" type="index" width="50">
        <template slot-scope="scope">
          <span>{{ (listQuery.pageNo - 1) * listQuery.pageSize + scope.$index + 1 }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="orderNum" align="center" label="订单编号" width="200" />
      <el-table-column prop="statusName" align="center" label="订单状态" />
      <el-table-column prop="accountName" align="center" label="账号名" />
      <el-table-column prop="orderTime" align="center" label="下单时间" width="200" />
      <el-table-column prop="consigneeName" align="center" label="收货人姓名">
        <template slot-scope="scope">
          <span v-if="scope.row.consigneeName !== ''">{{ scope.row.consigneeName }}</span>
          <span v-else>自提订单</span>
        </template>
      </el-table-column>
      <el-table-column prop="total" align="center" label="总金额">
        <template slot-scope="scope">
          {{ Number(scope.row.total).toFixed(2) }}
        </template>
      </el-table-column>
      <el-table-column align="center" fixed="right" label="操作" width="300">
        <template slot-scope="scope">
          <el-button class="text-button" size="mini" @click="handleDetail(scope.row.id)">详情</el-button>
          <!-- <el-button
            class="text-button"
            :disabled="scope.row.status === '1' || scope.row.status === '2'"
            size="mini"
            @click="handleDeliver(scope.row.id, scope.row.orderNum)"
          >发货
          </el-button> -->
          <!-- 收货方式 0->物流 ， 2->自提 如果是自提，那么置灰所有按钮-->
          <!-- :0->未发货; 1->已发货 ; 2->已收货; 3->异常 -->
          <el-button
            class="text-button"
            :disabled="scope.row.consigneeType === '2' || scope.row.status === '1' || scope.row.status === '2'"
            size="mini"
            @click="handleDeliver(scope.row.id, scope.row.orderNum)"
          >发货
          </el-button>
          <el-button
            class="text-button"
            :disabled="scope.row.consigneeType === '2' || scope.row.status === '2'"
            size="mini"
            @click="handleReceive(scope.row.id, scope.row.orderNum)"
          >收货</el-button>
          <el-button
            class="text-button"
            :disabled="scope.row.consigneeType === '2' || scope.row.status === '0'"
            size="mini"
            @click="handleLogistics(scope.row)"
          >物流</el-button>
          <!-- <el-button
            ref="copyButton"
            v-clipboard:copy="message"
            v-clipboard:success="onCopy"
            v-clipboard:error="onError"
            class="text-button"
            :disabled="scope.row.consigneeType === '2' || scope.row.status === '0'"
            size="mini"
            @click="handleLogistics(scope.row)"
          >物流</el-button> -->
          <el-button
            :class="scope.row.consigneeType === '2' || scope.row.status === '2' ? 'text-button' : 'text-button el-button--danger'"
            :disabled="scope.row.consigneeType === '2' || scope.row.status === '2'"
            size="mini"
            @click="handleAbnormal(scope.row.orderNum,scope.row.id)"
          >异常处理</el-button>
          <!-- <el-button
            :class="scope.row.consigneeType === '2'? 'text-button' : 'text-button el-button--danger'"
            size="mini"
            :disabled="scope.row.consigneeType === '2'"
            @click="handleDelete(scope.row.id)"
          >删除</el-button> -->
          <el-button
            class="text-button el-button--danger"
            size="mini"
            @click="handleDelete(scope.row.id)"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination
      :total-count="totalCount"
      :page.sync="listQuery.pageNo"
      :limit.sync="listQuery.pageSize"
      @pagination="getList"
    />
  </div>
</template>

<script>
import pagination from '@/components/pagination/index.vue'
import { commonMixin } from '@v/mixin/commonMixin.js'
import { orderShip, orderReceive, orderException, orderExport } from '@a/business/order.js'
import ComApiUrl from '@a/comomApi.js'
import { mapGetters } from 'vuex'
export default {
  components: { pagination },
  mixins: [commonMixin],
  data() {
    return {
      comApiUrlList: new ComApiUrl('/order/api/order/queryOrderList'),
      comApiUrlDelete: new ComApiUrl('/order/api/order/deleteOrderById/'),
      dialogFormVisible_deliver: false,
      dialogTitle_deliver: '确认发货信息',
      dialogFormVisible_Abnormal: false,
      dialogTitle_Abnormal: '异常信息处理',
      listQuery: {
        pageNo: 1,
        pageSize: 10,
        beginTime: '',
        endTime: '',
        accountId: ''
      },
      rules_deliver: {
        shipper: [
          { required: true, message: '发货人不能为空!', trigger: 'blur' }
        ]
      },
      rules_Abnormal: {
        name: [
          { required: true, message: '信息选择不能为空!', trigger: 'blur' }
        ]
      },
      // 发货
      formData_deliver: {
        id: '',
        orderNum: '',
        logistics: '',
        productNum: '',
        shipper: '',
        trackNum: ''
      },
      // 异常处理
      formData_Abnormal: {
        exceptionCause: '',
        orderNum: '',
        id: ''
      },
      exceptionCause: [ // 异常处理
        { label: '收款异常', value: '0' },
        { label: '缺货', value: '1' },
        { label: '物流异常', value: '2' },
        { label: '其他异常', value: '3' }
      ],
      userInfo: {},
      orderStatus: [ // 订单状态
        { label: '未发货', value: '0' }, { label: '已发货', value: '1' },
        { label: '已收货', value: '2' }, { label: '异常', value: '3' }
      ],
      message: '11111111'
    }
  },
  computed: {
    ...mapGetters(['logisticsList'])
  },
  mounted() {
    this.userInfo = JSON.parse(localStorage.getItem('userInfo'))
    this.listQuery.accountId = this.userInfo.userId
    this.getList()
  },
  methods: {
    getList() {
      const userInfo = JSON.parse(localStorage.getItem('userInfo'))
      this.listQuery.accountId = userInfo.userId
      this.getInfo()
    },
    // 重置
    handleReload() {
      this.listQuery = {
        pageNo: 1,
        pageSize: 10,
        accountId: this.userInfo.userId
      }
      this.getList()
    },
    dateChange(time) {
      console.log(time)
      this.listQuery.beginTime = time[0]
      this.listQuery.endTime = time[1]
    },
    // 导出
    handleExport() {
      orderExport(this.listQuery).then(res => {
        // const blob = new Blob([res.data]) // 低级错误
        const blob = new Blob([res])
        console.log(blob)
        const downloadElement = document.createElement('a')
        // 创建下载的链接
        const href = window.URL.createObjectURL(blob)
        downloadElement.href = href
        // 下载后的文件名
        downloadElement.download = `订单数据_${this.getNowTime()}.xls`
        document.body.appendChild(downloadElement)
        downloadElement.click() // 下载
        // 下载完成 移除 a
        document.body.removeChild(downloadElement)
        // 释放blob对象
        window.URL.revokeObjectURL(href)
      })
    },
    // 获取当前时间并格式化
    getNowTime() {
      const time = new Date()
      const y = time.getFullYear()
      let m = time.getMonth() + 1
      let d = time.getDate()
      let h = time.getHours()
      let mi = time.getMinutes()
      let s = time.getSeconds()
      m = m < 10 ? `0${m}` : m
      d = d < 10 ? `0${d}` : d
      h = h < 10 ? `0${h}` : h
      mi = mi < 10 ? `0${mi}` : mi
      s = s < 10 ? `0${s}` : s
      return `${y}${m}${d}${h}${mi}${s}`
    },
    // 详情
    handleDetail(id) {
      this.$router.push('/business/order/detail/' + id)
    },
    // 发货
    handleDeliver(id, orderNum) {
      this.formData_deliver.id = id
      this.formData_deliver.orderNum = orderNum
      this.dialogFormVisible_deliver = true
    },
    // 确定发货
    handleSave_deliver() {
      console.log(this.formData_deliver)
      orderShip(this.formData_deliver).then(res => {
        console.log(res)
        this.apiDealResult(res)
        this.dialogFormVisible_deliver = false
        this.getList()
        this.$refs.formData_deliver.resetFields()
      })
    },
    // 收货
    handleReceive(id, orderNum) {
      this.$confirm('是否确认该订单已收货?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: ''
      }).then(() => {
        orderReceive({ id, orderNum }).then(res => {
          this.apiDealResult(res)
          this.getList()
        })
      })
    },
    // 复制成功时的回调函数
    onCopy(e) {
      console.log(e)
      alert('111111111111')
    },
    // 复制失败时的回调函数
    onError(e) {
      alert('抱歉，复制失败！')
    },
    // 物流
    handleLogistics(row) {
      const { logistics, trackNum } = row
      if (logistics === 'zt') {
        window.open('https://www.zto.com/express/expressCheck.html')
      } else if (logistics === 'htky') {
        window.open('http://800bestex.com/bill/track')
      } else {
        window.open('http://www.kuaidi100.com/all/' + logistics + '.shtml?mscomnu=' + trackNum)
      }
    },
    // 异常处理
    handleAbnormal(orderNum, id) {
      this.dialogFormVisible_Abnormal = true
      this.formData_Abnormal.orderNum = orderNum
      this.formData_Abnormal.id = id
    },
    // 确定异常
    handleSave_Abnormal() {
      console.log(this.formData_Abnormal)
      orderException(this.formData_Abnormal).then(res => {
        this.apiDealResult(res)
        this.dialogFormVisible_Abnormal = false
        this.getList()
      })
    },
    // 接口处理结果封装
    apiDealResult(res) {
      if (res.code === 0) {
        this.$message({
          type: 'success',
          message: res.msg
        })
      } else {
        this.$message({
          type: 'error',
          message: res.msg
        })
      }
    }
  }
}
</script>
